import { createStore } from 'vuex'
const getData = () => {
  return new Promise((resolve, reject) => {
    let res = true
    setTimeout(() => {
      if (res) {
        let list = [{
          id: 1,
          name: 'jack-' + Math.floor((Math.random()*100)+1)
        },{
          id: 2,
          name: 'tom-' + Math.floor((Math.random()*100)+1)
        }]
        resolve(list)
      } else {
        reject({
          result: []
        })
      }
    }, 2000)
  })
}
const store = createStore({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false },
      { id: 3, text: '...', done: true }
    ],
    count: 111,
    list: []
  },
  getters: {
    doneTodos: (state) => {
      return state.todos.filter(todo => todo.done)
    },
    getTodoById: (state) => (id) => {
      return state.todos.find(todo => todo.id === id)
    }
  },
  mutations: {
    increment (state, payload) {
      state.count += payload.amount
    },
    decrement  (state, payload) {
      state.count -= payload.amount
    },
    gotData (state, payload) {
      state.list = payload
      console.log('gotData', payload)
    }
  },
  actions: {
    incrementAsync (context, payload) {
      setTimeout(() => {
        context.commit('increment', payload)
      }, 2000)
    },
    incrementAsyncThen (context, payload) {
      return new Promise((resolve, reject) => {
        let res = true
        setTimeout(() => {
          context.commit('increment', payload)
          if (res) {
            resolve({
              result: '已加上:' + payload.amount
            })
          } else {
            reject({
              result: '失败:' + payload.amount
            })
          }
        }, 2000)
      })
    },
    async actionA ({ commit }) {
      commit('gotData', await getData())
    },
    async actionB ({ dispatch, commit }, payload) {
      await dispatch('actionA') // 等待 actionA 完成
      commit('increment', payload)
    }
  }
})

export default store